package com.troila.cloud.simplify.web.controller;

import java.io.FileInputStream;
import java.util.List;

import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/wechat")
public class WechatRestController {

	@Autowired
	private WxMpService wechat;

//	@Autowired
//	private WxMpMessageRouter router;
	

	/**
	 * 验证开发服务器
	 */
	@GetMapping
	public String verify(String echostr, String timestamp, String nonce, String signature) {
		if (StringUtils.hasText(echostr)) {
			if (wechat.checkSignature(timestamp, nonce, signature)) {
				return echostr;
			}
		}
		return "";
	}

	/**
	 * 用户触发的事件、发送的消息等
	 */
//	@PostMapping
//	public String processMessage(String timestamp, String nonce, String signature, @RequestBody String msg) {
//		if (wechat.checkSignature(timestamp, nonce, signature)) {
//			WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(msg);
//			WxMpXmlOutMessage outMessage = router.route(inMessage);
//			if (outMessage != null) {
//				return outMessage.toXml();
//			}
//		}
//		return "";
//	}

	@GetMapping("/menu")
	public String menu(String file) {
		try {
			if (StringUtils.isEmpty(file)) {
				file = "menu1.json";
			}
			WxMenu menu = WxMenu.fromJson(new FileInputStream(file));
			processMenuButtons(wechat, menu.getButtons());
			wechat.getMenuService().menuCreate(menu);
			return wechat.getMenuService().menuGet().toJson();
		} catch (Exception e) {
			return e.getMessage();
		}
	}

	private void processMenuButtons(WxMpService svc, List<WxMenuButton> buttons) {
		for (WxMenuButton button : buttons) {
			if (button.getSubButtons() != null && !button.getSubButtons().isEmpty()) {
				processMenuButtons(svc, button.getSubButtons());
			} else {
				if (button.getType().toLowerCase().equals("view")) {
					String url = button.getUrl();
//					String redirect = svc.oauth2buildAuthorizationUrl(url, "snsapi_base", "");
					String redirect = svc.oauth2buildAuthorizationUrl(url, "snsapi_userinfo", "");
					button.setUrl(redirect);
				}
			}
		}
	}

}
